import { memo, createRef, PureComponent} from 'react'
import type { ReactNode } from 'react'
import AppAudio from './app-audio.ts'
import AppAudioContext from '@/Player/app-audio-context.ts'
import { Divider, Menu, ResizeBox, Slider, Space } from '@arco-design/web-react'
import { IconAction } from '@/components/web-react'
import { Dropdown } from '@arco-design/web-react';
import { getMusicList } from '@/apis/demo.ts'
import { minuteFoSecond } from '@/utils/format.ts'
import { IconClose, IconDelete, IconDoubleUp, IconDownload, IconStar } from '@arco-design/web-react/icon'
import { RIconLike, RIconLikeFill, RIconList, RIconLoop, RIconMute, RIconNext, RIconOrder, RIconPause, RIconPlay, RIconPrev, RIconRandom, RIconVolumeHigh, RIconVolumeLow, RIconVolumeMedium } from '@/components/web-react/icon.tsx'
import { useNavigate } from 'react-router'

interface IProps {
  children?: ReactNode
  history?: any
}

class AppPlayer extends PureComponent<IProps, any> {
  constructor(props: IProps) {
    super(props)

    this.state = {
      active: false,
      name: '',
      author: '',
      cover: '',
      currentAudioUrl: '',
      matedata: { currentTime: 0, duration: 0 },
      intervalID: 0,
      visible: false,
      playModule: <RIconOrder style={{fontSize: 21}}/>,
      playMuted: <RIconVolumeMedium style={{fontSize: 21}}/>,
      volume: 75
    }

  }
  private appPlayerRef = createRef<AppAudio>()
  // private appAudioContextRef = createRef<AppAudioContext>()

  async componentDidMount() {
    const appPlayer = new AppAudio()
    // const appAudioContext = new AppAudioContext()
    this.appPlayerRef.current = appPlayer
    // this.appAudioContextRef.current = appAudioContext
    try {
      const res = await getMusicList()
      appPlayer.musics = { list: res.data, label: 'audio' }
      appPlayer.onLoadedMetadata(() => this.resetMusic())
      appPlayer.circulate(() => this.resetMusic())
      window.removeEventListener('keydown', (e) => this.handleKeydown(e))
      window.addEventListener('keydown', (e) => this.handleKeydown(e))
    } catch (e) {
      console.log(e)
    }
  }
  handleKeydown(e:KeyboardEvent) {
    if (e.code === 'Space') {
      this.handlePlayTarget()
    }
  }
  resetMusic() {
    const appPlayer = this.appPlayerRef.current
    this.setState({
      active: appPlayer?.action,
      name: appPlayer?.music.name,
      author: appPlayer?.music.author,
      cover: appPlayer?.music.cover,
      currentAudioUrl: appPlayer?.music.audio,
      matedata: appPlayer?.matedate
    })
  }
  private upProgress() {
    const appPlayer = this.appPlayerRef.current
    this.setState({
      matedata: appPlayer?.matedate
    })
    let intervalID: any = this.state.intervalID
    if (!intervalID) {
      intervalID = setInterval(() => {
        this.setState({
          matedata: appPlayer?.matedate
        })
      }, 100)
      this.setState({
        intervalID
      })
    }
  }
  handlePlayTarget = () => {
    const appPlayer = this.appPlayerRef.current
    if (!appPlayer?.action) {
      this.upProgress()
      appPlayer?.play()
    } else {
      clearInterval(this.state.intervalID)
      this.setState({
        intervalID: 0
      })
      appPlayer.pause()
    }
    this.setState({ active: appPlayer?.action })
  }

  handlePrev = () => {
    const appPlayer = this.appPlayerRef.current
    appPlayer?.prev()
    this.resetMusic()
    this.upProgress()
  }

  handleNext = () => {
    const appPlayer = this.appPlayerRef.current
    appPlayer?.next()
    this.resetMusic()
    this.upProgress()
  }

  handlePlayModuleChange = (e: string) => {
    const appPlayer = this.appPlayerRef.current
    console.log(e);
    if (!e) {
      return
    }
    switch (e) {
      case 'loop':
        // 歌单循环
        appPlayer?.loop(false)
        appPlayer?.circulate(() => this.resetMusic())
        this.setState({
          playModule: <RIconLoop style={{fontSize: 21}}/>
        })
        break
      case 'order':
        // 顺序播放
        this.setState({
          playModule: <RIconOrder style={{fontSize: 21}}/>
        })
        break
      case 'random':
        appPlayer?.loop(true)
        this.setState({
          playModule: <RIconRandom style={{fontSize: 21}}/>
        })
        break
      default:
        break
    }
  }

  handlePlayMuted = (event: number) => {
    const appPlayer = this.appPlayerRef.current
    if (event === 0) {
      appPlayer?.muted(true)
      this.setState({
        playMuted: <RIconMute style={{fontSize: 21}}/>,
        volume: 0
      })
    } else {
      appPlayer?.muted(false)
      appPlayer?.volume(event)
      this.setState({
        volume: event
      })
      if( event < 30) {
        this.setState({
          playMuted: <RIconVolumeLow style={{fontSize: 21}}/>
        })
      }else if(event < 80) {
        this.setState({
          playMuted: <RIconVolumeMedium style={{fontSize: 21}}/>
        })
      }else {
        this.setState({
          playMuted: <RIconVolumeHigh style={{fontSize: 21}}/>
        })
      }
    }
  }
  handleUpdateCurrentTime = (param:unknown) => {
    const appPlayer = this.appPlayerRef.current
    appPlayer?.updateCurrentTime(param)
    this.upProgress()
  }
  handleDownload = (event: Event) => {
    // const appPlayer = this.appPlayerRef.current
    event.preventDefault() // 阻止默认的跳转行为
    const { currentAudioUrl } = this.state
    if (currentAudioUrl) {
      const link = document.createElement('a')
      link.href = currentAudioUrl
      link.download = `${this.state.name}--${this.state.author}` // 设置下载文件的名称
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }
  handleHistory = () => {
    const appPlayer = this.appPlayerRef.current
    return appPlayer?.history ? appPlayer.history : ['1']
  }


  render() {
    const { active, name, author, cover, matedata, visible, playModule, playMuted, volume } = this.state
    return (
      <div
        className={
          'w-full bg-primary-600 select-none fixed bottom-0 '
        }
      >
        <ResizeBox
          directions={['top']}
          style={{ minHeight: '4rem', maxHeight: '6rem'}}
          className='h-4'
          resizeTriggers={{top: <Divider style={{margin: '0'}}/>}}
        >
          <div className={'w-full h-full flex px-[7%] gap-2'}>
            <div className={'flex gap-x-2 items-center border-r pr-4 mr-4 w-56 text-white'}>
              <div
                className={`w-[56px] h-[56px] bg-primary-600 bg-no-repeat bg-cover bg-center shadow rounded-lg content-center hover:rounded cursor-pointer transition duration-200`}
                style={{ backgroundImage: `url('${cover}')` }}
              ></div>
              <div className={'flex flex-col justify-center truncate max-w-32'}>
                <span className={'text-nowrap '}>{name}</span>
                <span className={'text-nowrap text-xs scale-90 origin-left text-gray-200'}>{author}</span>
              </div>
            </div>
            <div className={'flex-1 flex gap-x-2 justify-center items-center flex-col'}>
              <div className={'flex items-center gap-x-2'}>
                <Dropdown
                  trigger={'click'}
                  position='tr'
                  droplist={
                    <Menu onClickMenuItem={(k:string) => this.handlePlayModuleChange(k)}>
                      <Menu.Item key="loop">
                        <RIconLoop style={{
                          marginRight: 8,
                          fontSize: 16,
                          transform: 'translateY(1px)',
                        }}/>
                        <span className='text-primary-600'>单曲循环</span>
                      </Menu.Item>
                      <Menu.Item key="order">
                        <RIconOrder style={{
                          marginRight: 8,
                          fontSize: 16,
                          transform: 'translateY(1px)',
                        }}/>
                        <span className='text-primary-600'>顺序播放</span>
                      </Menu.Item>
                      <Menu.Item key="random">
                        <RIconRandom style={{
                          marginRight: 8,
                          fontSize: 16,
                          transform: 'translateY(1px)',
                        }}/>
                        <span className='text-primary-600'>随机播放</span>
                      </Menu.Item>
                    </Menu>
                  }
                >
                  <span className='mr-8'>{playModule}</span>
                </Dropdown>
                <Space>
                  <RIconPrev onClick={this.handlePrev} size='21px'/>
                  {
                    !active
                    ?<RIconPlay size='21px' onClick={this.handlePlayTarget}/>
                    :<RIconPause size='21px' onClick={this.handlePlayTarget}/>
                  }
                  <RIconNext size='21px' onClick={this.handleNext}/>
                </Space>
                <Dropdown
                  trigger={'click'}
                  position='tr'
                  droplist={
                    <div className='bg-primary-400 py-2 rounded'>
                      <Slider
                        vertical={true}
                        min={0}
                        max={100}
                        defaultValue={volume}
                        onChange={(e) => this.handlePlayMuted(e as number)}
                      ></Slider>
                    </div>
                  }
                >
                  <span className={'ml-8 transition duration-250'}>
                  {playMuted}
                </span>
                </Dropdown>
              </div>
              <div className={'w-full flex items-center justify-around text-primary-300'}>
              <span className={'scale-75'}>{`${minuteFoSecond(matedata.currentTime)}`}</span>
                <Slider
                  value={matedata.currentTime}
                  min={0}
                  max={matedata.duration}
                  tooltipVisible={false}
                  style={{ width: '81%', backgroundColor: '#8B96D9' }}
                  onChange={(e) => this.handleUpdateCurrentTime(e)}
                ></Slider>
                <span className={'scale-75'}>{`${minuteFoSecond(matedata.duration)}`}</span>
              </div>
            </div>
            <div className={'w-[20em] flex justify-center items-center gap-x-4'}>
              <IconDoubleUp style={{ fontSize: '21px', color: '#d5d5fa' }} className={"cursor-pointer"}/>
              <Dropdown popupVisible={visible} droplist={<PlayerList onClose={()=> this.setState({ visible: false })} />} position='tr' trigger={'click'}>
                <span><RIconList onClick={() => this.setState({ visible: !visible })}/></span>
              </Dropdown>
              {/* <IconAction names={['like','like-full']} size={21}></IconAction> */}
              <RIconLike size='21px'></RIconLike>
              <IconDownload style={{ fontSize: '21px', color: '#d5d5fa' }}className={"cursor-pointer"} />
            </div>
          </div>
        </ResizeBox>
      </div>
    )
  }
}

export default memo(AppPlayer)

interface IPlayerListProps {
  onClose: () => void
}

interface IPlayerListState {
  list: {
    name: string
    author: string
    duration: string
    action: string
  }[]
}

class PlayerList extends PureComponent<IPlayerListProps, IPlayerListState> {
  constructor(props: IPlayerListProps) {
    super(props)
    this.state = {
      list: [
        {
          name: '歌曲名',
          author: '歌手',
          duration: '时长',
          action: '操作'
        },
        {
          name: '歌曲名',
          author: '歌手',
          duration: '时长',
          action: '操作'
        },
        {
          name: '歌曲名',
          author: '歌手',
          duration: '时长',
          action: '操作'
        },
        {
          name: '歌曲名歌曲名',
          author: '歌手',
          duration: '时长',
          action: '操作'
        },
        {
          name: '歌曲名歌曲名歌曲名',
          author: '歌手',
          duration: '时长',
          action: '操作'
        }
      ]
    }
  }

  render() {
    const { list } = this.state
    return (
      <div className={"relative w-[49em] h-[27em] font-light bg-white rounded-sm shadow-md flex flex-col select-none"}>
        <div className={"w-full h-[3em] text-white bg-primary-600 rounder-t-sm flex justify-between items-center box-border px-4 py-2"}>
          <span className={" font-medium"}>播放列表（）</span>
          <div className={"flex items-center gap-x-2"}>
            <div className='flex items-center cursor-pointer active:text-primary-300 '><IconStar style={{fontSize: '18px'}}/> 收藏全部</div>
            <div className='flex items-center cursor-pointer active:text-primary-300'><IconDelete style={{fontSize: '18px'}}/> 清除</div>
            <div onClick={() => this.props.onClose()} className='flex items-center cursor-pointer active:text-primary-300'><IconClose style={{fontSize: '18px'}}/></div>
          </div>
        </div>
        <div className={"flex-1 w-full m-0 overflow-y-auto custom-scrollbar bg-slate-50"}>

        </div>
      </div>
    )
  }
}



